#include "signup.h"
#include "ui_signup.h"
#include "databasemanager.h"
#include "logonwindow.h"
#include <QMessageBox>
#include <QSqlError>

signup::signup(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::signup)
{
    ui->setupUi(this);
}

signup::~signup()
{
    delete ui;
}

void signup::registerUser(const QString &id, const QString &password)
{
    QSqlQuery query(DatabaseManager::getDatabase());
    query.prepare("INSERT INTO user(ID, Password, Focus, Fruit, Achieve) "
                  "VALUES (:id, :password, 0, 0, 0)");
    query.bindValue(":id", id);
    query.bindValue(":password", password);
    if (!query.exec()) {
        qDebug() << "Sign up:Failed to insert data into database:" << query.lastError().text();
    }
}

void signup::on_pushButton_clicked()
{
    QString id = ui->lineEdit->text();
    QString password = ui->lineEdit_2->text();
    QString confirmPassword = ui->lineEdit_3->text();

    if (password == confirmPassword) {
        registerUser(id, password);
        QMessageBox::information(this, tr("Success"), tr("注册成功！"));
        logonwindow *logon=new logonwindow;
        logon->show();
        this->close();
    } else {
        QMessageBox msgBox;
        msgBox.setText("密码不一致！请重新输入");
        msgBox.setWindowTitle("");
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
    }
}

